<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">地理位置 API</h1>
        <p class="text-gray-300 text-lg">
          获取用户的地理位置信息，支持实时位置跟踪和位置变化监听
        </p>
      </div>

      <!-- 位置获取区域 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">位置获取</h2>
        
        <div class="flex flex-wrap gap-4 mb-6">
          <button
            @click="getCurrentPosition"
            :disabled="isLoading"
            class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-location mr-2"></i>
            {{ isLoading ? '获取中...' : '获取当前位置' }}
          </button>
          
          <button
            @click="watchPosition"
            :disabled="isWatching"
            class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-location-heart mr-2"></i>
            {{ isWatching ? '正在监听...' : '开始位置监听' }}
          </button>
          
          <button
            @click="stopWatching"
            :disabled="!isWatching"
            class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-stop mr-2"></i>
            停止监听
          </button>
        </div>

        <!-- 错误信息 -->
        <div v-if="error" class="mb-6 p-4 bg-red-900/30 border border-red-600 rounded-lg">
          <div class="flex items-center mb-2">
            <i class="i-carbon-warning text-red-500 text-xl mr-3"></i>
            <span class="text-red-400 font-semibold">获取位置失败</span>
          </div>
          <p class="text-gray-300">{{ error }}</p>
        </div>

        <!-- 位置信息显示 -->
        <div v-if="currentPosition" class="bg-gray-800 rounded-lg p-6">
          <h3 class="text-lg font-semibold text-white mb-4">当前位置信息</h3>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 基本位置信息 -->
            <div>
              <h4 class="text-tech-accent font-semibold mb-3">坐标信息</h4>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-400">纬度:</span>
                  <span class="text-white font-mono">{{ currentPosition.coords.latitude.toFixed(6) }}°</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-400">经度:</span>
                  <span class="text-white font-mono">{{ currentPosition.coords.longitude.toFixed(6) }}°</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-400">精度:</span>
                  <span class="text-white">{{ Math.round(currentPosition.coords.accuracy) }} 米</span>
                </div>
                <div v-if="currentPosition.coords.altitude !== null" class="flex justify-between">
                  <span class="text-gray-400">海拔:</span>
                  <span class="text-white">{{ Math.round(currentPosition.coords.altitude!) }} 米</span>
                </div>
                <div v-if="currentPosition.coords.altitudeAccuracy !== null" class="flex justify-between">
                  <span class="text-gray-400">海拔精度:</span>
                  <span class="text-white">{{ Math.round(currentPosition.coords.altitudeAccuracy!) }} 米</span>
                </div>
              </div>
            </div>

            <!-- 运动信息 -->
            <div>
              <h4 class="text-tech-accent font-semibold mb-3">运动信息</h4>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-400">方向:</span>
                  <span class="text-white">
                    {{ currentPosition.coords.heading !== null ? `${Math.round(currentPosition.coords.heading)}°` : '未知' }}
                  </span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-400">速度:</span>
                  <span class="text-white">
                    {{ currentPosition.coords.speed !== null ? `${(currentPosition.coords.speed * 3.6).toFixed(1)} km/h` : '未知' }}
                  </span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-400">获取时间:</span>
                  <span class="text-white">{{ formatTimestamp(currentPosition.timestamp) }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 地图链接 -->
          <div class="mt-6 pt-4 border-t border-gray-700">
            <div class="flex flex-wrap gap-3">
              <a
                :href="getGoogleMapsUrl(currentPosition.coords)"
                target="_blank"
                class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                <i class="i-carbon-map mr-1"></i>
                在 Google 地图中查看
              </a>
              <a
                :href="getOpenStreetMapUrl(currentPosition.coords)"
                target="_blank"
                class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                <i class="i-carbon-earth mr-1"></i>
                在 OpenStreetMap 中查看
              </a>
              <button
                @click="copyCoordinates(currentPosition.coords)"
                class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                <i class="i-carbon-copy mr-1"></i>
                复制坐标
              </button>
            </div>
          </div>
        </div>

        <div v-else-if="!isLoading && !error" class="text-center text-gray-400 py-12">
          <i class="i-carbon-location text-4xl mb-4 block mx-auto opacity-50"></i>
          <p>点击上方按钮获取您的位置信息</p>
        </div>
      </div>

      <!-- 位置历史 -->
      <div v-if="positionHistory.length > 0" class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-4 text-white">位置历史</h3>
        
        <div class="space-y-3 max-h-64 overflow-y-auto">
          <div
            v-for="(position, index) in positionHistory.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-4"
          >
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <div class="text-white font-mono text-sm">
                  {{ position.coords.latitude.toFixed(6) }}, {{ position.coords.longitude.toFixed(6) }}
                </div>
                <div class="text-gray-400 text-xs mt-1">
                  精度: {{ Math.round(position.coords.accuracy) }}m | 
                  时间: {{ formatTimestamp(position.timestamp) }}
                </div>
              </div>
              <button
                @click="showOnMap(position.coords)"
                class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-xs transition-colors"
              >
                查看
              </button>
            </div>
          </div>
        </div>
        
        <div class="mt-4 pt-4 border-t border-gray-700">
          <button
            @click="clearHistory"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
          >
            <i class="i-carbon-trash-can mr-1"></i>
            清空历史
          </button>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>所有现代浏览器都支持地理位置 API</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要方法</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.geolocation.getCurrentPosition()</code> - 获取当前位置</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.geolocation.watchPosition()</code> - 监听位置变化</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.geolocation.clearWatch()</code> - 停止位置监听</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>地图和导航应用</li>
              <li>基于位置的服务和推荐</li>
              <li>天气和本地信息服务</li>
              <li>运动和健身追踪</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">隐私和权限</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>需要用户明确授权才能访问位置</li>
              <li>HTTPS 环境下体验更佳</li>
              <li>用户可以随时撤销位置权限</li>
              <li>应当明确告知用户位置使用目的</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

// 响应式状态
const currentPosition = ref<GeolocationPosition | null>(null)
const positionHistory = ref<GeolocationPosition[]>([])
const isLoading = ref(false)
const isWatching = ref(false)
const error = ref('')
let watchId: number | null = null

// 获取当前位置
const getCurrentPosition = () => {
  if (!navigator.geolocation) {
    error.value = '您的浏览器不支持地理位置功能'
    return
  }

  isLoading.value = true
  error.value = ''

  navigator.geolocation.getCurrentPosition(
    (position) => {
      currentPosition.value = position
      positionHistory.value.push(position)
      isLoading.value = false
    },
    (err) => {
      isLoading.value = false
      handleGeolocationError(err)
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 60000
    }
  )
}

// 开始位置监听
const watchPosition = () => {
  if (!navigator.geolocation) {
    error.value = '您的浏览器不支持地理位置功能'
    return
  }

  error.value = ''
  isWatching.value = true

  watchId = navigator.geolocation.watchPosition(
    (position) => {
      currentPosition.value = position
      positionHistory.value.push(position)
    },
    (err) => {
      handleGeolocationError(err)
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 60000
    }
  )
}

// 停止位置监听
const stopWatching = () => {
  if (watchId !== null) {
    navigator.geolocation.clearWatch(watchId)
    watchId = null
  }
  isWatching.value = false
}

// 处理地理位置错误
const handleGeolocationError = (err: GeolocationPositionError) => {
  switch (err.code) {
    case err.PERMISSION_DENIED:
      error.value = '用户拒绝了位置访问请求。请在浏览器设置中允许位置访问。'
      break
    case err.POSITION_UNAVAILABLE:
      error.value = '位置信息不可用。请检查您的网络连接和GPS设置。'
      break
    case err.TIMEOUT:
      error.value = '获取位置信息超时。请重试。'
      break
    default:
      error.value = '获取位置时发生未知错误。'
      break
  }
}

// 格式化时间戳
const formatTimestamp = (timestamp: number): string => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 生成 Google 地图 URL
const getGoogleMapsUrl = (coords: GeolocationCoordinates): string => {
  return `https://www.google.com/maps?q=${coords.latitude},${coords.longitude}`
}

// 生成 OpenStreetMap URL
const getOpenStreetMapUrl = (coords: GeolocationCoordinates): string => {
  return `https://www.openstreetmap.org/?mlat=${coords.latitude}&mlon=${coords.longitude}&zoom=15`
}

// 复制坐标
const copyCoordinates = async (coords: GeolocationCoordinates) => {
  const text = `${coords.latitude}, ${coords.longitude}`
  try {
    await navigator.clipboard.writeText(text)
    // 这里可以添加一个成功提示
  } catch (err) {
    console.error('复制失败:', err)
  }
}

// 在地图中显示
const showOnMap = (coords: GeolocationCoordinates) => {
  window.open(getGoogleMapsUrl(coords), '_blank')
}

// 清空历史记录
const clearHistory = () => {
  positionHistory.value = []
}
</script>
